// 用户端热门推荐云函数
const db = uniCloud.database();
const _ = db.command;

// 获取热门推荐壁纸
exports.main = async (event, context) => {
  try {
    // 获取请求参数
    const { limit = 6 } = event;
    
    // 查询热门壁纸（按下载量和收藏量排序）
    const res = await db.collection('wallpaper')
      .where({
        status: true // 只查询已上线的壁纸
      })
      .orderBy('download_count', 'desc') // 按下载量降序
      .limit(Number(limit))
      .get();
    
    // 如果热门数据不足，补充最新数据
    let wallpapers = res.data;
    if (wallpapers.length < Number(limit)) {
      const needMore = Number(limit) - wallpapers.length;
      const existingIds = wallpapers.map(w => w._id);
      
      const supplementRes = await db.collection('wallpaper')
        .where({
          _id: _.nin(existingIds),
          status: true
        })
        .orderBy('create_time', 'desc')
        .limit(needMore)
        .get();
      
      wallpapers = [...wallpapers, ...supplementRes.data];
    }
    
    // 获取当前用户的收藏状态（如果已登录）
    const openid = context?.OPENID || '';
    
    if (openid) {
      // 查询用户收藏记录
      const favoriteRes = await db.collection('favorite')
        .where({
          openid: openid,
          wallpaper_id: _.in(wallpapers.map(w => w._id))
        })
        .get();
      
      const favoriteIds = favoriteRes.data.map(f => f.wallpaper_id);
      
      // 设置收藏状态
      wallpapers = wallpapers.map(wallpaper => ({
        ...wallpaper,
        is_favorite: favoriteIds.includes(wallpaper._id)
      }));
    } else {
      // 未登录用户，全部设置为未收藏
      wallpapers = wallpapers.map(wallpaper => ({
        ...wallpaper,
        is_favorite: false
      }));
    }
    
    return {
      code: 200,
      data: wallpapers,
      message: '获取热门推荐成功'
    };
  } catch (error) {
    console.error('获取热门推荐失败:', error);
    return {
      code: 400,
      message: '获取热门推荐失败',
      error: error.message
    };
  }
};